<script setup lang="ts">
import { ElMessage } from 'element-plus'
import type { Props, Emits } from './utils/types'
import type { UploadProps, } from 'element-plus'

const $props = defineProps<Props>()
const $emit = defineEmits<Emits>()

const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    imageUrl.value = response.data.file
    ElMessage.success('上传成功')
    $emit('update:modelValue', response.data.file)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('只能上传JPG格式图片')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('只能上传小于5MB的图片')
        return false
    }
    return true
}

const url = import.meta.env.VITE_APP_API_URL

</script>

<template>
    <div class="upload">
        <el-upload class="avatar-uploader" :action="`${url}/upload/file`" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" accept="image/*">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <div v-else class="avatar-uploader-icon">
                <img src="./images/upload.png" alt="upload">
                <div class="text">{{ title }}</div>
            </div>
        </el-upload>
    </div>
</template>

<style lang="scss">
.avatar-uploader {
    .el-upload {
        border: 1px solid var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .avatar-uploader-icon {
        font-size: 12px;
        color: #BBBBBB;
        width: 95px;
        text-align: center;
        height: 61px;

        div {
            line-height: 1em;
            margin: 10px 0;
        }

        img {
            width: 24px;
            height: 24px;
            display: block;
            margin: 0 auto;
            margin-top: 5px;
            object-fit: cover;
        }
    }
}
</style>

<style lang="scss" scoped>
.upload {
    line-height: 0 !important;

    .avatar-uploader .avatar {
        width: 95px;
        height: 61px;
        display: block;
        object-fit: cover;
    }

}
</style>
